package com.wshl.aijiuunion.controller.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.stx.xhb.xbanner.XBanner;
import com.wshl.aijiuunion.GlobConstant;
import com.wshl.aijiuunion.NetUrl;
import com.wshl.aijiuunion.R;
import com.wshl.aijiuunion.callback.RequestCallback;
import com.wshl.aijiuunion.controller.activity.SearchActivity;
import com.wshl.aijiuunion.controller.activity.WebActivity;
import com.wshl.aijiuunion.model.RequestModel;
import com.wshl.aijiuunion.utils.BarUtils;
import com.wshl.aijiuunion.utils.GlideUtils;
import com.wshl.aijiuunion.utils.ImagePreviewUtils;
import com.wshl.aijiuunion.utils.share.LoginOutUtils;
import com.wshl.aijiuunion.view.adapter.GoodsAdapter;
import com.wshl.aijiuunion.view.adapter.ShopFenLeiAdapter;
import com.wshl.aijiuunion.view.bean.Bannerbean;
import com.wshl.aijiuunion.view.bean.GoodsBean;
import com.wshl.aijiuunion.view.bean.ShopDataBean;
import com.wshl.aijiuunion.view.bean.ShopFenleiBeans;
import com.wshl.aijiuunion.view.widget.RoundCornerImageView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.bingoogolapple.baseadapter.BGAOnRVItemClickListener;

/**
 * Created buy 风凊扬 on 2019/10/21 0021
 */
public class ShopFragment extends TabFragment implements OnRefreshListener {
    @BindView(R.id.shop_banner)
    XBanner xbanner;
    @BindView(R.id.et_shop_search)
    EditText etShopSearch;
    @BindView(R.id.recycle_shop_fenlei)
    RecyclerView recycleShopFenlei;
    @BindView(R.id.img_left)
    RoundCornerImageView imgLeft;
    @BindView(R.id.img_righttop)
    RoundCornerImageView imgRighttop;
    @BindView(R.id.img_rightbottom)
    RoundCornerImageView imgRightbottom;
    @BindView(R.id.recycle_tuijian)
    RecyclerView recycleGoods;
    Unbinder unbinder;
    @BindView(R.id.refresh_shop)
    SmartRefreshLayout mRefresh;
    @BindView(R.id.rl_shop1)
    RelativeLayout rlShop1;
    @BindView(R.id.img_gouwuche)
    ImageView imgGouwuche;

    private RequestModel shopModel;

    @Override
    public void initImmersionBar() {
        BarUtils.setStatusBarForFragment(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        LogUtils.i("shopfragment--onCreateView");
        View view = inflater.inflate(R.layout.fragment_shop, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        LogUtils.i("shopfragment--onActivityCreated");
        mRefresh.setOnRefreshListener(this);
        mRefresh.setEnableLoadMore(false);//禁止上拉加载更多
        shopModel = new RequestModel();
        //分类
        recycleShopFenlei.setLayoutManager(new GridLayoutManager(mContext, 4));

        //推荐商品
        recycleGoods.setLayoutManager(new GridLayoutManager(mContext, 2));
        // recycleGoods.setLayoutManager(new StaggeredGridLayoutManager(2, LinearLayout.VERTICAL));

        recycleGoods.setHasFixedSize(true);
        recycleGoods.setNestedScrollingEnabled(false);


        getShopData(NetUrl.MALL);
    }


    private GoodsAdapter goodsAdapter;
    private ShopFenLeiAdapter shopFenLeiAdapter;
    private List<ShopFenleiBeans> shopFenleiBeansList;
    private List<GoodsBean> goodsBeanList;


    private void getShopData(String url) {

        shopModel.getShopData(mContext, new RequestCallback() {
            @Override
            public void onSuccess(String response) {
                mRefresh.finishRefresh();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.has("code")) {
                        String code = jsonObject.getString("code");
                        switch (code) {
                            case GlobConstant.REQUESTSUCCESS:
                                ShopDataBean shopDataBean = GsonUtils.fromJson(response, ShopDataBean.class);
                                ShopDataBean.DataBean data = shopDataBean.getData();
                                List<ShopDataBean.DataBean.BgBean> bg = data.getBg();//背景图
                                if (bg != null && bg.size() > 0) {
                                    setBanner(bg);
                                }
                                List<ShopDataBean.DataBean.CategoryBean> category = data.getCategory();//分类


                                setFenlei(category);
                                List<ShopDataBean.DataBean.ProductBean> product = data.getProduct();//推荐商品
                                setGoods(product);
                                break;
                            case GlobConstant.REQUESTERROR://token过期失效
                                LoginOutUtils.reLogin(mContext);
                                break;
                            default:
                                if (jsonObject.has("msg")) {
                                    ToastUtils.showLong(jsonObject.getString("msg"));
                                }
                                break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(int code) {
                mRefresh.finishRefresh();
                LogUtils.e("商城首页:" + code);
            }

            @Override
            public void onIntentError() {

                mRefresh.finishRefresh();
            }
        });

    }

    private void setGoods(List<ShopDataBean.DataBean.ProductBean> product) {

        if (product != null && product.size() > 0) {
            goodsBeanList = new ArrayList<>();
            for (ShopDataBean.DataBean.ProductBean productBean : product) {

                goodsBeanList.add(new GoodsBean(productBean.getCover(), productBean.getId(), productBean.getOld_price(), productBean.getPrice(), productBean.getSales(), productBean.getSku(), productBean.getTitle()));

            }

            goodsAdapter = new GoodsAdapter(recycleGoods);
            goodsAdapter.setData(goodsBeanList);
            recycleGoods.setAdapter(goodsAdapter);
        }

    }

    private void setFenlei(List<ShopDataBean.DataBean.CategoryBean> category) {


        if (category != null && category.size() > 0) {
            shopFenleiBeansList = new ArrayList<>();

            for (ShopDataBean.DataBean.CategoryBean categoryBean : category) {
                shopFenleiBeansList.add(new ShopFenleiBeans(categoryBean.getCat_name(), categoryBean.getCover(), categoryBean.getId()));
            }

            shopFenLeiAdapter = new ShopFenLeiAdapter(recycleShopFenlei);
            shopFenLeiAdapter.setOnRVItemClickListener(new BGAOnRVItemClickListener() {
                @Override
                public void onRVItemClick(ViewGroup parent, View itemView, int position) {

                    String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);
                    int id = shopFenleiBeansList.get(position).getId();
                    Intent intent = new Intent(mContext, WebActivity.class);
                    intent.putExtra(GlobConstant.WEBURL, NetUrl.GOODSLIST + token + "&id=" + id);
                    // intent.putExtra(GlobConstant.WEBURL, "http://www.baidu.com");
                    ActivityUtils.startActivity(intent);
                }
            });
            shopFenLeiAdapter.setData(shopFenleiBeansList);
            recycleShopFenlei.setAdapter(shopFenLeiAdapter);
        }
    }

    private void setBanner(final List<ShopDataBean.DataBean.BgBean> bg) {
        List<Bannerbean> banners = new ArrayList<>();
        final List<String> imageUrls = new ArrayList<>();
        for (ShopDataBean.DataBean.BgBean bgBean : bg) {
            imageUrls.add(NetUrl.IMG + bgBean.getCover());
            banners.add(new Bannerbean(NetUrl.IMG + bgBean.getCover()));
        }


        xbanner.setBannerData(banners);
        xbanner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                //  LogUtils.i("图片:" + ((Bannerbean) model).getXBannerUrl());
                GlideUtils.loadImage(mContext, ((Bannerbean) model).getXBannerUrl(), (ImageView) view);

            }
        });
        xbanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, Object model, View view, int position) {

                //点击图片预览
                //  ImagePreviewUtils.previewImg(mContext, imageUrls, position);


                String linkurl = bg.get(position).getLinkurl();
                Intent intent = new Intent(mContext, WebActivity.class);
                intent.putExtra(GlobConstant.WEBURL, linkurl);
                ActivityUtils.startActivity(intent);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        getShopData(NetUrl.MALL);
    }

    @OnClick({R.id.et_shop_search, R.id.img_gouwuche})
    public void onViewClicked(View view) {
        String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);
        if (TextUtils.isEmpty(token)) {
            LoginOutUtils.reLogin(mContext);
            return;
        }
        switch (view.getId()) {
            case R.id.et_shop_search:
                ActivityUtils.startActivity(SearchActivity.class);
                break;
            case R.id.img_gouwuche:

                Intent intent = new Intent(mContext, WebActivity.class);
                intent.putExtra(GlobConstant.WEBURL, NetUrl.GOUWUCHE + token);
                ActivityUtils.startActivity(intent);
                break;

        }
    }


    private void startWeb(String token, String keyword) {
        Intent intent = new Intent(mContext, WebActivity.class);
        intent.putExtra(GlobConstant.WEBURL, NetUrl.GOODSLIST + token + "&type=" + keyword);
        ActivityUtils.startActivity(intent);
    }

    @OnClick({R.id.img_left, R.id.img_righttop, R.id.img_rightbottom})
    public void onListViewClicked(View view) {
        String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);
        switch (view.getId()) {
            case R.id.img_left:
                startWeb(token, "1");
                break;
            case R.id.img_righttop:
                startWeb(token, "2");
                break;
            case R.id.img_rightbottom:
                startWeb(token, "3");
                break;
        }
    }
}
